<?php
function listavailabletires( $atts ) {
	$atts          = shortcode_atts( array(
		'mins'          => 5,
		'option'        => 'listavailabletires',
		'tire_quantity' => ">",
		'tire_is_sabok' => "1"
	), $atts );
	$seconds       = 60 * intval( $atts['mins'] );
	$seconds       = $seconds < 60 ? 60 : $seconds;
	$tire_is_sabok = intval( $atts['tire_is_sabok'] );
	$option        = $atts['option'];
	global $wpdb;
	require( tiremanager_plugin_dir_path . 'formsconfig.php' );
	require( tiremanager_plugin_dir_path . 'sellers_brands.php' );
	/** @var string $tire_table_quantities_without_prefix_name */
	$table_name = $wpdb->prefix . $tire_table_option;

	$query          = "SELECT `id`, `create_date`, `create_by`, `last_modified_date`,
 						`option_key`, `option_description`, `option_value` 
 						FROM `$table_name` 
 						WHERE `option_key` LIKE '$option'
";
	$tire_db_result = $wpdb->get_row( $query );
	if ( $tire_db_result == null ) {
		$listavailabletires_content = listavailabletires_get_content_from_db( $tire_is_sabok, $atts['tire_quantity'] );
		$content                    = listavailabletires_create_content_string( $listavailabletires_content );
		$wpdb->insert( $table_name, array(
			'create_date'        => current_time( 'mysql', 1 ),
			'last_modified_date' => current_time( 'mysql', 1 ),
			'option_key'         => $option,
			'option_value'       => $content
		) );

		return $content;
	}
	$last_modified_date = date_create( $tire_db_result->last_modified_date )->getTimestamp();
	$now                = time();
	if ( $now - $last_modified_date < $seconds ) {
		return $tire_db_result->option_value;
	}
	$listavailabletires_content = listavailabletires_get_content_from_db( $tire_is_sabok, $atts['tire_quantity'] );
	$content                    = listavailabletires_create_content_string( $listavailabletires_content );
	$wpdb->update( $table_name,
		array(
			'option_value'       => $content,
			'last_modified_date' => current_time( 'mysql' )
		),
		array( 'option_key' => $option ) );

	return $content;

	return $tire_db_result['option_value'];
}

function listavailabletires_get_content_from_db( $tire_is_sabok = 1, $tire_quantity = ">" ) {
	global $wpdb;
	require( tiremanager_plugin_dir_path . 'formsconfig.php' );
	require( tiremanager_plugin_dir_path . 'sellers_brands.php' );
	if ( ! function_exists( 'jdate' ) ) {
		date_default_timezone_set( 'Asia/Tehran' );
		include( tiremanager_plugin_dir_path . 'lib/jdf.php' );
	}
	$table_name = $wpdb->prefix . $tire_table_quantities_without_prefix_name;
	$query      = "select * from $table_name where id in (select max(id)
							from $table_name
							group by tire_seller, tire_brand, tire_size)
							and tire_is_active =1 
							and tire_type_is_sabok = $tire_is_sabok 
							and tire_quantity $tire_quantity 0
";
	$results    = $wpdb->get_results( $query );
	$data       = [];

	foreach ( $results as $row ) {
		$date_updated = date_create( $row->date_updated, timezone_open( 'UTC' ) );
		$timestamp    = $date_updated->getTimestamp();

		$last_update = jdate( 'l Y-m-d H:i', $timestamp, '', 'Asia/Tehran', 'en' );
		$ro          = [
			$row->tire_size,
			$brands_array[ $row->tire_brand ]['farsi_name'],
			$sellers_array[ $row->tire_seller ]['farsi_name'],
			$row->tire_quantity,
			$last_update
		];
		array_push( $data, $ro );

	}

	return $data;
}

function listavailabletires_create_content_string( $listavailabletires_content, $last_modified_date = null ) {
	if ( $last_modified_date == null ) {
		$last_modified_date = date_create()->getTimestamp();
	}
	if ( ! function_exists( 'jdate' ) ) {
		date_default_timezone_set( 'Asia/Tehran' );
		include( tiremanager_plugin_dir_path . 'lib/jdf.php' );
	}
	$last_update = jdate( 'l Y-m-d H:i', $last_modified_date, '', 'Asia/Tehran', 'en' );

	$listavailabletires_content = json_encode( $listavailabletires_content );
	$rand                       = rand();
	$content =  "
<div>
<h6>آخرین به‌روزرسانی:
 <br>
 $last_update</h6>
<link rel='stylesheet' href='https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css' >
<script src='https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js' ></script>
<table id='listavailabletires$rand' style='width: inherit'></table>
		<script>
		const listavailabletires_content$rand = JSON.parse('$listavailabletires_content'); 
		jQuery(function() {
    jQuery('#listavailabletires$rand').DataTable( {
        data: listavailabletires_content$rand,
            responsive: true,
            pageLength:25,
              \"scrollX\": true,
              scrollY: true,
                  \"bLengthChange\": false,
                      \"order\": [[ 0, 'asc' ], [ 3, 'desc' ]],
        columns: [
            { title: \"سایز\" },
            { title: \"برند\" },
            { title: \"عامل\" },
            { title: \"تعداد\" },
            { title: \"تاریخ به‌روزرسانی\" },
        ],
         language: {
    \"sEmptyTable\":     \"هیچ داده‌ای در جدول وجود ندارد\",
    \"sInfo\":           \"نمایش _START_ تا _END_ از _TOTAL_ ردیف\",
    \"sInfoEmpty\":      \"نمایش 0 تا 0 از 0 ردیف\",
    \"sInfoFiltered\":   \"(فیلتر شده از _MAX_ ردیف)\",
    \"sInfoPostFix\":    \"\",
    \"sInfoThousands\":  \",\",
    \"sLengthMenu\":     \"نمایش _MENU_ ردیف\",
    \"sLoadingRecords\": \"در حال بارگزاری...\",
    \"sProcessing\":     \"در حال پردازش...\",
    \"sSearch\":         \"جستجو:\",
    \"sZeroRecords\":    \"رکوردی با این مشخصات پیدا نشد\",
    \"oPaginate\": {
        \"sFirst\":    \"برگه‌ی نخست\",
        \"sLast\":     \"برگه‌ی آخر\",
        \"sNext\":     \"بعدی\",
        \"sPrevious\": \"قبلی\"
    },
    \"oAria\": {
        \"sSortAscending\":  \": فعال سازی نمایش به صورت صعودی\",
        \"sSortDescending\": \": فعال سازی نمایش به صورت نزولی\"
    }
}
    } );
} );
</script>
</div>
		";


	return $content;


}

add_shortcode( 'listavailabletires', 'listavailabletires' );
